import configparser
import os

# from shark.utils.logger import Logger
from utils.logger import Logger

logger = Logger('Config').getlogger()


class Config():

    def __init__(self, ini_file):
        self.conf = configparser.ConfigParser()
        self.ini_file = ini_file

    def read_section(self):
        self.conf.read(self.ini_file, 'utf-8')
        sections = self.conf.sections()
        return sections

    def write_section(self, section_name):
        self.conf.read(self.ini_file, 'utf-8')
        if not self.conf.has_section(section_name):
            self.conf.add_section(section_name)
            self.conf.write(open(self.ini_file, "w"))
            # logger.info(f'{section_name}已添加')
        else:
            logger.info(f'{section_name}已存在')

    def delete_section(self, section_name):
        # 删除整个section下的所有option和value
        self.conf.read(self.ini_file, 'utf-8')
        if self.conf.has_section(section_name):
            self.conf.remove_section(section_name)
            logger.info(f'{section_name}已移除')
            self.conf.write(open(self.ini_file, "w"))
        else:
            logger.info(f'{section_name}不存在')

    def read_option(self, section_name):
        self.conf.read(self.ini_file, 'utf-8')
        options = self.conf.options(section_name)
        return options

    def write_option_and_value(self, section_name, option_name, value='None'):
        self.conf.read(self.ini_file, 'utf-8')
        if not self.conf.has_option(section_name, option_name):
            self.conf.set(section_name, option_name, value)
            self.conf.write(open(self.ini_file, "w"))
            # logger.info(f'{value}已添加')
        else:
            # logger.info(f'{value}已存在')
            self.conf.set(section_name, option_name, value)
            self.conf.write(open(self.ini_file, "w"))
            # logger.info(f'{value}已更新')

    def delete_option(self, section_name, option_name):
        self.conf.read(self.ini_file, 'utf-8')
        if self.conf.has_option(section_name, option_name):
            self.conf.remove_option(section_name, option_name)
            self.conf.write(open(self.ini_file, "w"))
            logger.info(f'{option_name}已移除')
        else:
            logger.info(f'{option_name}不存在')

    def read_value(self, section_name, option_name):
        self.conf.read(self.ini_file, 'utf-8')
        value = self.conf.get(section_name, option_name)
        # 类型是字符串
        return value

# if __name__ == '__main__':
# config = Config()
# sec = config.read_section()
# print(sec)
# config.write_section('caichang')
# config.delete_section('caichang')

# options = config.read_option('mailinfo')
# print(options)
#
# config.write_option_and_value('caichang','name','jince')
# config.delete_option('caichang','name')

# value = config.read_value('mysqldb','sql_pass')
# print(value)
# print(type(value))
